package com.jiamingZhao.mapper.factory;

import com.jiamingZhao.cache.CacheMap;
import com.jiamingZhao.sessoin.SqlSession;
import com.jiamingZhao.sessoin.SqlSessionFactory;

import java.lang.reflect.Proxy;

public class MapperProxyFactory {

    public static <T> T newInstance(Class<T> clazz) {
        final MapperProxy<T> mapperProxy = new MapperProxy<>(SqlSessionFactory.getSqlSession(), clazz);
        @SuppressWarnings("unchecked")
        T t = (T) Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{clazz},
                mapperProxy
        );
        return t;
    }

    public static <T> T getMapper(Class<T> type) {
        T proxy = CacheMap.getMapperProxy(type);
        if (proxy == null) {
            proxy = CacheMap.addMapperProxy(type, MapperProxyFactory.newInstance(type));
        }
        return proxy;
    }

}